<script setup>
import {createRouter as $router, useRoute} from "vue-router";
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {router} from "@/router/index.js";
import {userStore} from "@/store/index.js";

const route = useRoute();
const userItemStore = userStore();
// 获取传递的车辆配置和ID
const carConfig = {
  id: route.query.id, // 车辆ID
  color: route.query.color,
  wheel: route.query.wheel,
  seat: route.query.seat,
  colorPrice: Number(route.query.colorPrice),
  wheelPrice: Number(route.query.wheelPrice),
  seatPrice: Number(route.query.seatPrice),
  totalPrice: Number(route.query.totalPrice),
  imgs: route.query.carImageUrl,
  address: route.query.fullAddress,
  name: route.query.name,
  telephone: route.query.telephone,
};

const car = ref(null);
const carTye = ref(null);
const isSubmitting = ref(false); // 控制提交按钮的状态
const isBackButtonDisabled = ref(false); // 控制返回按钮的禁用状态

const getCarById = async () => {
  try {
    const response = await axios.get(`/car/getCarById`, {params: {id: carConfig.id}});
    car.value = response.data;
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const getCarTypeById = async () => {
  try {
    const response = await axios.get(`/carType/findById`, {params: {id: carConfig.id}});
    carTye.value = response.data;
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const checkLoginAndNavigate = (routeName, productId) => {
  if (userItemStore.loggedIn) {
    router.push({name: routeName, params: {id: productId}});
  } else {
    router.push({name: 'login'});
    ElMessage.warning('请先登录')
  }
};

const submitOrder = () => {
  const order = {
    productId: carConfig.id,
    carPrice: carConfig.totalPrice,
    carColor: carConfig.color,
    carWheel: carConfig.wheel,
    carSeat: carConfig.seat,
    price: (carConfig.totalPrice * 0.01).toFixed(0),
    address: carConfig.address || null,
    name:carConfig.name,
    telephone:carConfig.telephone,
    imgs: carConfig.imgs,
    status: 1,
  };
  // 禁用提交按钮和返回按钮
  isSubmitting.value = true;
  isBackButtonDisabled.value = true;

  axios.post('/productsOrders/addOrder', order).then((response) => {
    const orderId = response.data.id;
    ElMessage.success("订单已提交成功,订单编号：" + orderId);

    // 5秒后跳转到其他界面
    setTimeout(() => {
      router.push({
        path: "/myOrder/carOrder",});
    }, 5000);

    // 20秒后恢复按钮状态
    setTimeout(() => {
      isSubmitting.value = false;
      isBackButtonDisabled.value = false;
    }, 20000);
  }).catch((error) => {
    ElMessage.error(error.message);
    // 错误时恢复按钮状态
    isSubmitting.value = false;
    isBackButtonDisabled.value = false;
  });
};

onMounted(() => {
  getCarById();
  getCarTypeById();
});
</script>

<template>
  <div class="vehicle-detail">
    <h2 class="title">车辆配置详情</h2>

    <div v-if="car && carTye" class="vehicle-info">
      <div class="card">
        <div class="vehicle-header">
          <h3>车辆信息</h3>
        </div>
        <div class="vehicle-body">
          <p><strong>车辆ID：</strong>{{ car.name }}</p>
          <p><strong>车辆类型：</strong>{{ carTye.categoryName }}</p>
          <p><strong>综合耗油量（EU）：</strong>{{ car.fuelConsumption }} 升/100公里</p>
          <p><strong>最高车速：</strong>{{ car.maxSpeed }} 公里/小时</p>
          <p><strong>百公里加速：</strong>{{ car.acceleration }} 秒</p>
          <p><strong>车辆能源：</strong>{{ car.energy }}</p>
          <p><strong>车辆座位数：</strong>{{ car.seatCount }}</p>
        </div>
      </div>

      <div class="card">
        <div class="vehicle-header">
          <h3>车辆配置</h3>
        </div>
        <div class="vehicle-body">
          <p><strong>车身颜色：</strong>
            <span
                :style="{ backgroundColor: carConfig.color, padding: '5px 10px', borderRadius: '5px', color: '#a4e3c5' }">{{
                carConfig.color
              }}</span>
          </p>
          <p><strong>车轮选择：</strong>{{ carConfig.wheel }}</p>
          <p><strong>座椅选择：</strong>{{ carConfig.seat }}</p>
          <p><strong>总价：</strong>¥{{ carConfig.totalPrice }}</p>
          <p style="color: red"><strong>购车意向金：</strong>¥{{ (carConfig.totalPrice * 0.01).toFixed(0) }}</p>
        </div>
      </div>

      <div class="card">
        <div class="vehicle-header">
          <h3>个人信息</h3>
        </div>
        <div class="vehicle-body">
          <p><strong>姓名：</strong>{{ carConfig.name }}</p>
          <p><strong>手机号：</strong>{{ carConfig.telephone }}</p>
        </div>
        <div class="vehicle-body">
          <p><strong>地址：</strong>
            <span v-if="carConfig.address&& carConfig.address !== ' '">{{ carConfig.address }}</span>
            <span v-else>暂未填写（没有填写地址我们后续会通过您留下的手机号联系您去附近的销售点取车） </span>
          </p>
          <div style="text-align: right; margin-top: 50px;">
            <p>*注：获取地址信息,帮助选择您附近的销售点，后期方便我们与您联系</p>
          </div>
        </div>
      </div>

    </div>

    <div class="vehicle-image">
      <img :src="carConfig.imgs" alt="车辆图片"/>
    </div>

    <!-- 提交订单和返回按钮 -->
    <div class="submit-order">
      <button @click="submitOrder" class="submit-btn" :disabled="isSubmitting">提交订单</button>
      <button @click="checkLoginAndNavigate('configure', carConfig.id)" class="back-btn"
              :disabled="isBackButtonDisabled">返回上一步
      </button>
    </div>
  </div>
</template>

<style scoped>
.vehicle-detail {
  width: 80%;
  margin: 20px auto;
  font-family: Arial, sans-serif;
}

.title {
  text-align: center;
  font-size: 2rem;
  margin-bottom: 20px;
}

.vehicle-info {
  margin-bottom: 30px;
}

.card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.vehicle-header {
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.vehicle-body {
  font-size: 1rem;
}

.vehicle-body p {
  margin-bottom: 8px;
}

.vehicle-image {
  text-align: center;
  margin-top: 20px;
}

.vehicle-image img {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
  border-radius: 8px;
}

.submit-order {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.submit-btn,
.back-btn {
  background-color: #409eff;
  color: white;
  padding: 10px 25px;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 48%;
}

.submit-btn:hover,
.back-btn:hover {
  background-color: #66b1ff;
}

.submit-btn:focus,
.back-btn:focus {
  outline: none;
}

.submit-btn {
  background-color: #66b1ff;
}

.back-btn {
  background-color: #f4f4f4;
  color: #409eff;
}

.submit-btn:disabled,
.back-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
